﻿using Cinemachine;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//默认状态下始终跟随玩家
public class CameraController : MonoBehaviour
{
    private CinemachineVirtualCamera m_virtualCamera;
    private CinemachineConfiner m_confiner;
    private Transform transform_player;
    private CinemachineCameraOffset m_cameraOffset;
    private EventSystem eventSystem;

    private float defaultSize;              //默认相机大小

    private void Awake()
    {
        eventSystem = Service.Get<EventSystem>();
        m_virtualCamera = GetComponent<CinemachineVirtualCamera>();
        m_confiner = GetComponent<CinemachineConfiner>();
        m_cameraOffset = GetComponent<CinemachineCameraOffset>();

        defaultSize = m_virtualCamera.m_Lens.OrthographicSize;
        transform_player = Character.Instance.transform;
        m_virtualCamera.Follow = transform_player;
    }

    private void OnEnable()
    {
        eventSystem.PlayerDie += MyReset;
    }
    private void OnDisable()
    {
        eventSystem.PlayerDie -= MyReset;
    }

    public void SetConfiner(PolygonCollider2D polygonCollider)
    {
        if ( polygonCollider == m_confiner.m_BoundingShape2D)
            return;
        m_confiner.m_BoundingShape2D = polygonCollider;
    }

    public void MyReset()
    {
        StopAllCoroutines();
        m_virtualCamera.m_Lens.OrthographicSize = defaultSize;
        m_cameraOffset.m_Offset = Vector3.zero;
    }

    public void StartMove(CameraMove cameraMove)
    {
        StartCoroutine(Move(cameraMove));
        eventSystem.CameraMove?.Invoke(true);
    }

    private IEnumerator Move(CameraMove move)
    {
        List<SingleCameraMove> singleCameraMoves = move.singleCameraMoves;
        
        float timer;
        for (int i = 0; i < singleCameraMoves.Count; i++)
        {
            SingleCameraMove singleCameraMove = singleCameraMoves[i];
            float duration = singleCameraMove.Duration;
            Vector3 deltaOffset;
            if (singleCameraMove.Destination == SingleCameraMove.IDLE)
                deltaOffset = SingleCameraMove.IDLE;
            else
            {
                if (duration < 0.1f)
                {
                    m_cameraOffset.m_Offset = singleCameraMove.Destination - m_virtualCamera.Follow.position.RemoveZ() - m_cameraOffset.m_Offset.RemoveZ();
                    continue;
                }
                deltaOffset = Time.fixedDeltaTime / duration * (singleCameraMove.Destination - m_virtualCamera.Follow.position.RemoveZ() - m_cameraOffset.m_Offset.RemoveZ());
            }

            for (timer = 0; timer < duration; timer += Time.fixedDeltaTime)
            {
                m_cameraOffset.m_Offset += deltaOffset;
                yield return new WaitForFixedUpdate();
            }
        }
        m_cameraOffset.m_Offset = Vector3.zero;
        eventSystem.CameraMove?.Invoke(false);
    }
}
